(function($){

    UE.getEditor('editor');

    function initProvince() {
        var data = SysArea.province();
        var box = $('#bp_province');
        box.find('option').each(function(i){
            if(i > 0) {
                $(this).remove();
            }
        });
        for(var i=0; i<data.length; i++) {
            box.append('<option value="'+ data[i] +'">'+ data[i] +'</option>');
        }
        $(box.find('option').get(0)).attr('selected', 'selected');
    }
    function initCity(p) {
        var data = SysArea.city(p);
        var box = $('#bp_city');
        box.find('option').each(function(i){
            if(i > 0) {
                $(this).remove();
            }
        });
        for(var i=0; i<data.length; i++) {
            box.append('<option value="'+ data[i] +'">'+ data[i] +'</option>');
        }
        $(box.find('option').get(0)).attr('selected', 'selected');
    }
    function initDistrict(p, c) {
        var data = SysArea.city(p, c);
        var box = $('#bp_district');
        box.find('option').each(function(i){
            if(i > 0) {
                $(this).remove();
            }
        });
        for(var i=0; i<data.length; i++) {
            box.append('<option value="'+ data[i][0] +'">'+ data[i][1] +'</option>');
        }
        $(box.find('option').get(0)).attr('selected', 'selected');
    }
    function initArea() {
        var pObj = $('#bp_province');
        var cObj = $('#bp_city');
        var dObj = $('#bp_district');
        initProvince();
        pObj.on('change', function(){
            var o = $(this);
            initCity(o.val());
        });
        cObj.on('change', function(){
            var o = $(this);
            initDistrict($('#bp_province').val(), o.val());
        });
    }
    function initAddPhoto() {
        var but = $('#but_add_photo');
        but.on('click', function(){
            var box = $('#bp_photos_box');
            box.append('<div class="input-group paddingTB5"><input type="file" class="form-control" name="bp_photos[]"><div class="input-group-addon bg_red cursor_pointer" onclick="$.bpPhotoDel(this)"><i class="fa fa-times"></i></div></div>');
        });
    }
    function initSelectMap() {
        $('#but_map_select').on('click', function(){
            layer.open({
                type: 2,
                title: '选择坐标',
                shadeClose: false,
                shade: 0.8,
                area: ['95%', '95%'],
                content: $(this).attr('durl') + '?callback=parent.setMapValue'
            });
        });
    }
    function setMapValue(obj) {
        //console.log(obj);
        $('#bp_coordinate').val(obj.lng + ',' + obj.lat);
        layer.closeAll();
        return true;
    }
    function initSelectTags() {
        $('#but_tags_select').on('click', function(){
            layer.open({
                type: 2,
                title: '选择标签',
                shadeClose: false,
                shade: 0.8,
                area: ['500px', '475px'],
                content: $(this).attr('durl') + '?callback=parent.setTagsValue&tags=' + $('#bp_tags').val()
            });
        });
    }
    function setTagsValue(ids, values) {
        $('#bp_tags').val(ids);
        $('#bp_tags_view').val(values);
        layer.closeAll();
    }
    function formResult(msg, state) {
        layer.closeAll();
        if(state == 0) {
            layer.alert(msg, {icon: 5});
        } else {
            layer.confirm('添加成功！', {icon: 6, title:'系统提示', btn: ['确定']}, function(index){
                location.href = $('#form_add').attr('urlList')
            });
        }
    }
    $.extend({
        'bpPhotoDel': function(obj) {
            $(obj).parent().remove();
        }
    });
    $(function(){
        initArea();
        initAddPhoto();
        initSelectMap();
        initSelectTags();
        window.setMapValue = setMapValue;
        window.setTagsValue = setTagsValue;
        window.formResult = formResult;
        $('#form_add').on('valid.form', function(e, form){
            // 必须传一张轮播图
            var fileNull = true;
            $('#bp_photos_box input').each(function(){
                var v = $(this).val();
                if(!!v) {
                    fileNull = false;
                }
            });
            if(fileNull) {
                layer.alert('轮播图片必须上传一张！', {icon: 5});
                return;
            }
            layer.load();
            form.submit();
        });

        $('#time').daterangepicker({
            "autoUpdateInput": false,
            "showDropdowns": true,
            "startDate": false,
            "timePicker": true,
            "timePicker24Hour": true,
            "timePickerIncrement": 1,
            "autoApply": true,
            "locale": {
                "format": "HH:mm",
                "separator": " 至 ",
                "applyLabel": "确 定",
                "cancelLabel": "取 消",
                "fromLabel": "From",
                "toLabel": "To",
                "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"],
                "monthNames": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                "firstDay": 1
            },
            "opens": "right",
            "drops": "down",
            "buttonClasses": "btn btn-sm",
            "applyClass": "btn-success",
            "cancelClass": "btn-default"
        }, function(start, end, label) {
        });
        $('#time').on('apply.daterangepicker', function(ev, picker) {
            $(this).val(picker.startDate.format('HH:mm') + ' 至 ' + picker.endDate.format('HH:mm'));
        });
        $('#time').on('cancel.daterangepicker', function(ev, picker) {
            $(this).val('');
        });


        $('#add_equipment').click(function(){
            var $text = $('#add_equipmentText').val();
            var html ="";
            html+= '<div class="input-group">' +
                '<input type="text" class="form-control del_equipmentText" name="facilities[]" readonly value="'+$text+'">' +
                '<div class="input-group-addon bg_337ab7 cursor_pointer del_equipment"><i class="fa fa-trash-o"></i> 删除</div>' +
                '</div>';
            var $delText = $('.del_equipmentText').length;

            var $delArr = [];

            $('.del_equipmentText').each(function () {
                $delArr.push($(this).val());
            });

            if($text) {
                if( $delText > 2) {
                    layer.msg('最多只能添加三个',{icon: 2});
                } else if($.inArray($text,$delArr) > -1) {
                    layer.msg('不能重复添加',{icon: 2});
                }
                else {
                    $('#delBox').append(html);
                }

            }

            $('.del_equipment').click(function(){
                $(this).parent().remove();
            })
        })


        $('#form_add').validator({
            rules: {
                decimal: function (element, params) {
                    //内部的this指向的是当前实例，可以直接调用所有方法，这里调用了test方法
                    return /^[0-9]+\.[0-9]{0,2}$/.test(element.value) || /^[0-9]+$/.test(element.value) || '请输入格式如: 12.59 或 12 的数字';
                }
            }
        });

    });
})(jQuery);